package com.baitiaojun.system.admin.controller.user;

import com.baitiaojun.common.constants.HttpStatus;
import com.baitiaojun.common.constants.MsgConstants;
import com.baitiaojun.common.domain.model.result.CommonResult;
import com.baitiaojun.ratelimit.core.annotation.RateLimit;
import com.baitiaojun.repeatsubmit.core.annotation.SubmitRepeat;
import com.baitiaojun.security.core.domain.LoginUser;
import com.baitiaojun.security.core.domain.UserInfo;
import com.baitiaojun.security.core.utils.SecurityUtils;
import com.baitiaojun.system.admin.controller.user.req.UserRegisterReq;
import com.baitiaojun.system.admin.controller.user.resp.UserInfoResp;
import com.baitiaojun.system.admin.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.netty.http.client.HttpClient;

import javax.annotation.security.PermitAll;

@Slf4j
@RestController
@Api("用户模块")
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PermitAll
    @SubmitRepeat
    @RateLimit(key = "register", count = 1, time = 5, RATE_LIMIT_TYPE = RateLimit.RateLimitType.IP)
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public CommonResult userRegister(@RequestBody @Validated UserRegisterReq registerReq) {
        log.info("===================开始注册===================");
        userService.userRegister(registerReq);
        log.info("===================注册成功===================");
        return CommonResult.ok(HttpStatus.SUCCESS, MsgConstants.REGISTER_SUCCESS_MSG);
    }

    @PreAuthorize("@permit.hasAnyPermission('*:*:*,system:user:query')")
    @ApiOperation("用户查询")
    @GetMapping("/userinfo")
    public CommonResult getUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserInfo userInfo = loginUser.getUserInfo();
        UserInfoResp userInfoResp = UserInfoResp.builder()
                .userInfo(userInfo).permissions(loginUser.getPermissions()).build();
        return CommonResult.ok(userInfoResp);
    }
}
